package org.malred.v1.server;

import org.malred.v1.server.HttpProtocolUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * minicat主类
 */
public class Bootstrap {
    /**
     * socket监听的端口号
     */
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * minicat启动需要初始化展开的一些操作
     */
    public void start() throws IOException {
        //todo minicat v1.0,http://localhost:8080,返回固定字符串到页面
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("minicat start on port: " + port);
        while (true) {
            //阻塞监听,直到连接
            Socket socket = serverSocket.accept();
            //有了socket,接收到请求
            OutputStream outputStream = socket.getOutputStream();
            // 不符合http
//            outputStream.write("Hello Mincat".getBytes());
//            socket.close();
            //响应信息
            String data = "Hello Mincat";
            String responseText =
                    HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }
    }
}
